package VMM;
import java.util.ArrayList;

/**
 * TLB which implements a FIFO replacement policy using two arrayLists
 * 
 * @author xvb09137
 * @changelog 16/2/12 switched if statements in put method. should only check
 *            for over capacity if the pageNo exists.
 * 
 *            17/2/12 Check for already existing frame, update this value.
 *            18/2/12 Code cleanup and comment
 */
public class TLBfifo implements ITLB {

	private int capacity;
	private ArrayList<Integer> pNo, fNo;

	public TLBfifo(int cap) {
		capacity = cap;
		fNo = new ArrayList<Integer>();
		pNo = new ArrayList<Integer>();
	}

	/**
	 * Place a page and frame number in the TLB
	 */
	public void put(int pageNo, int frameNo) {
		if (containsFrame(frameNo)) // if frame already exists
			pNo.set(fNo.indexOf(frameNo), pageNo);// reassign the frame's page
		else {
			if (this.pNo.size() == capacity)
				replace();// full capacity replace an entry

			pNo.add(pageNo);
			fNo.add(frameNo);
		}
	}

	/**
	 * Replace the first entry added 
	 */
	private void replace() {
		pNo.remove(0);
		fNo.remove(0);
	}

	/**
	 * Reports whether a page is stored in TLB
	 */
	public boolean containsPage(int page) {
		return pNo.contains(page);
	}

	/**
	 * Reports whether a frame is stored in TLB
	 */
	public boolean containsFrame(int frame) {
		return fNo.contains(frame);
	}

	/**
	 * Get the frame associated with page
	 */
	public int getFrameNo(int pageNo) {
		return (Integer) fNo.get(pNo.indexOf(pageNo));

	}
}
